home *** CD-ROM | disk | FTP | other *** search
- Path: news.mindlink.net!news
- From: genew@mindlink.bc.ca (Gene Wirchenko)
- Newsgroups: comp.lang.c
- Subject: Re: Examples of using "volatile"?
- Date: Fri, 19 Jan 1996 06:53:15 GMT
- Organization: MIND LINK! - British Columbia, Canada
- Message-ID: <4dnf7f$1sa@fountain.mindlink.net>
- References: <4djoj2$mr1@post.gsfc.nasa.gov> <4dm91p$bsi@info.uah.edu>
- NNTP-Posting-Host: line121.nwm.mindlink.net
- X-Newsreader: Forte Free Agent 1.0.82
-
- gbacon@oreo (Greg Bacon) wrote:
-
- >Stephen Maher (Stephen.Maher@gsfc.nasa.gov) wrote:
- >: Hi,
-
- >: I'd like a concrete example(s) illustrating a reason to
- >: use the "volatile" type qualifier.
-
- >: I understand the *theory* behind volatile (e.g., to
- >: avoid unwanted side-effects?). I also realize it's
- >: probably implementation dependent. But some examples
- >: from any implementation should help me understand
- >: its use a little better.
-
- >: Thanks,
-
- >: Steve
-
- >OK... say for example you have this:
-
- >void foo(void)
- >{
- > int i = 7;
-
- > if (i == 7)
- > {
- > /* do something */
- > }
- >}
-
- >Most optimizers will go ahead and lose the comparison since i _has_
- >to be equal to 7, right? Well, not always.. say you have some
- >interrupt handler (ahh, the random joy of interrupts) that might
- >come in and modify the value of i (highly unlikely, I admit, but this
- >is a highly oversimplified example). Well, if the optimizer
- >cuts out the test, then it won't matter whether the handler came
- >in. The correct version of foo() for this app would look like this:
-
- >void foo(void)
- >{
- > volatile int i = 7;
-
- > if (i == 7)
- > {
- > /* do something */
- > }
- >}
-
- >Basically, like most modifiers, volatile is a hint to the compiler
- >that the value of i could change at any time, and not to take its
- >value for granted. Of course, the compiler could ignore you since
- >it's only a hint, but that wouldn't be a very good compiler :)
-
- No, it wouldn't because it would be broken. K&R2, used as a sub
- for the Standard by those of us without $120 or so to spend on said
- Standard, says on page 211 (in the indented portion at the bottom):
- "The purpose of volatile is to force an implementation to
- suppress optimization that could otherwise occur."
- Note the word "force".
-
- >Hope this helps,
- >Greg
- >--
- >Greg Bacon <gbacon@cs.uah.edu>
- >University of Alabama in Huntsville
- >CS Department Systems Support Team
-
- Sincerely,
-
- Gene Wirchenko
-
- C Pronunciation Guide:
- y=x++; "wye equals ex plus plus semicolon"
- x=x++; "ex equals ex doublecross semicolon"
-
-